package com.qsmx.qingqiuticket.app.delegate.back;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.loader.AtmosLoader;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateMachineSettingBinding;
import com.qsmx.qingqiuticket.app.delegate.UsbPrintHomeDelegate;
import com.qsmx.qingqiuticket.app.entity.AdvEntity;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.InitMachineEntity;
import com.qsmx.qingqiuticket.app.event.HomeRefreshBannerEvent;
import com.qsmx.qingqiuticket.app.event.HomeRefreshEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.service.HeartBeatService;
import com.qsmx.qingqiuticket.app.util.ApkManager;
import com.qsmx.qingqiuticket.app.util.OpenUDID;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.Objects;

public class MachineSettingDelegate extends AtmosDelegate {
    private boolean isFirst;
    private DelegateMachineSettingBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_machine_setting;
    }

    public static MachineSettingDelegate create(boolean isFirst) {

        final Bundle args = new Bundle();
        args.putBoolean(FusionTag.IS_FIRST, isFirst);

        final MachineSettingDelegate delegate = new MachineSettingDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            isFirst = args.getBoolean(FusionTag.IS_FIRST);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBinding = DelegateMachineSettingBinding.bind(rootView);
        initView();
        onClick();


    }

    private void initView() {
        if (isFirst) {
            mBinding.btBack.setVisibility(View.GONE);
        } else {
            mBinding.btBack.setVisibility(View.VISIBLE);
        }

        mBinding.tvMachineMac.setText(OpenUDID.getOpenUDID());
        mBinding.etStoreNum.setText(AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
        mBinding.etMachineNum.setText(AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
    }

    private void onClick() {
        mBinding.btBack.setOnClickListener(v -> {
            getSupportDelegate().pop();
        });

        mBinding.btSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMachine();
            }
        });

    }

    private void initMachine() {
        AtmosLoader.showLoading(getContext());
        JSONObject params = new JSONObject();
        params.put("storeShortName", Objects.requireNonNull(mBinding.etStoreNum.getText()).toString().trim());
        params.put("cashierNo", Objects.requireNonNull(mBinding.etMachineNum.getText()).toString().trim());
        if (StringUtil.isEmpty(OpenUDID.getOpenUDID())) {
            params.put("mac", "1");
        } else {
            params.put("mac", OpenUDID.getOpenUDID());
        }
        params.put("version", ApkManager.getVersionName(getContext()));

        HttpHelper.RestClientPostRaw(params, HttpUrl.INIT_DATE,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        AtmosLoader.stopLoading();
                        try {
                            Type type = new TypeToken<InitMachineEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            InitMachineEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                AtmosPreference.addCustomStringPre(FusionPre.STORE_NUM, mBinding.etStoreNum.getText().toString());
                                AtmosPreference.addCustomStringPre(FusionPre.MACHINE_NUM, mBinding.etMachineNum.getText().toString());
                                AtmosPreference.addCustomStringPre(FusionPre.STORE_NAME, mData.getBody().getStoreName());
                                AtmosPreference.addCustomStringPre(FusionPre.MINI_CODE, mData.getBody().getQrCode());
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_BRAND_NAME, mData.getBody().getPrintBrandName());
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_STORE_NAME, mData.getBody().getPrintStoreName());

                                initAdv();

                                Intent serviceIntent = new Intent(getContext(), HeartBeatService.class);
                                getProxyActivity().startService(serviceIntent);
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), getContext().getString(R.string.service_error), "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        AtmosLoader.stopLoading();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        AtmosLoader.stopLoading();
                        DialogUtil.showCardErrorDialog(getContext(), getContext().getString(R.string.un_know_net_error), "确定");
                    }
                });
    }

    private void initAdv() {
        try {
            JSONObject params = new JSONObject();
            params.put("storeShortName", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM));
            params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
            HttpHelper.RestClientPostRaw(params, HttpUrl.GET_ADV,
                    new ISuccess() {
                        @Override
                        public void onSuccess(int code, String response) {
                            try {
                                Type type = new TypeToken<AdvEntity>() {
                                }.getType();
                                Gson gson = new Gson();
                                AdvEntity mData = gson.fromJson(response, type);
                                if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                    FusionData.mAdvData = mData;
                                    if (isFirst) {
//                                    getSupportDelegate().pop();
//                                    EventBus.getDefault().post(new HomeRefreshEvent(new Bundle()));
                                        getSupportDelegate().start(UsbPrintHomeDelegate.create(isFirst));
                                    } else {
                                        showLongToast("机台设置成功");
                                        EventBus.getDefault().post(new HomeRefreshBannerEvent(new Bundle()));
                                    }
                                } else {
                                    DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                                }
                            } catch (Exception e) {
                                DialogUtil.showCardErrorDialog(getContext(), getContext().getString(R.string.service_error), "确定");
                            }
                        }
                    }, new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                        }
                    }, new IFailure() {
                        @Override
                        public void onFailure() {
                            DialogUtil.showCardErrorDialog(getContext(), getContext().getString(R.string.un_know_net_error), "确定");
                        }
                    });
        } catch (Exception e) {
            DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
        }

    }
}
